package com.xysd.express.activity.logistics;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.xysd.express.R;
import com.xysd.express.adapter.map.searchAdapter;
import com.xysd.express.base.BaseActivity;
import com.xysd.express.bean.map.SearchModel;
import com.xysd.express.eventbus.LocationEvent;
import com.xysd.express.rx.RxBus;
import com.xysd.express.util.ActivityTaskManeger;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

@ContentView(R.layout.activity_map)
public class MapActivity extends BaseActivity implements TextWatcher,
        View.OnClickListener, AMapLocationListener {

    @ViewInject(R.id.mapView)
    private MapView mapView;
    @ViewInject(R.id.search_et)
    private TextView search_et;

    AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    LatLng latLng;
    @ViewInject(R.id.dingLocation)
    private ImageView dingLocation;
    @ViewInject(R.id.addressRecycler)
    private RecyclerView addressRecycler;
    private searchAdapter adapter;

    private String type;//从哪来的

    @Override
    protected void init() {
        type=getIntent().getStringExtra("type");
        search_et.addTextChangedListener(this);
        dingLocation.setOnClickListener(this);
        adapter = new searchAdapter(R.layout.map_item_layout, this, 0);
        addressRecycler.setLayoutManager(new LinearLayoutManager(this));
        addressRecycler.setAdapter(adapter);
        search_et.setOnClickListener(this);
        adapter.setCall(new searchAdapter.itemCall() {
            @Override
            public void itemClick(SearchModel item) {
                RxBus.getInstance().post(new LocationEvent(item,type));
                ActivityTaskManeger.getInstance().closeActivity();
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar("选择地址");
        initMap(savedInstanceState);
    }

    private AMapLocationClient mlocationClient;
    public AMapLocationClientOption mLocationOption = null;

    private void initMap(Bundle savedInstanceState) {
        mapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        mlocationClient = new AMapLocationClient(this);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(100));
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setScrollGesturesEnabled(true);
        aMap.getUiSettings().setAllGesturesEnabled(true);
        aMap.setMyLocationEnabled(true);// 设置为
        mlocationClient.setLocationListener(this);
        mlocationClient.startLocation();
        mlocationClient.setLocationOption(mLocationOption);
        initLocation();
    }

    private void initLocation() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.7f);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.mipmap.zuobiao));
        myLocationStyle.strokeWidth(5);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(30.0f)); //缩放比例
        //添加一个圆
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.radius(20.0f);
        aMap.addCircle(circleOptions);
        //设置amap的属性
        UiSettings settings = aMap.getUiSettings();
        settings.setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (mlocationClient!=null){
            mlocationClient.stopLocation();
            mlocationClient=null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 开始进行poi搜索
     */
    private List<SearchModel> models = new ArrayList<>();

    protected void doSearchQuery(final String address) {
        PoiSearch.Query query = new PoiSearch.Query(address, "", "");
        final PoiSearch search = new PoiSearch(this, query);
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);
        search.setOnPoiSearchListener(
                new PoiSearch.OnPoiSearchListener() {
                    @Override
                    public void onPoiSearched(PoiResult poiResult, int errcode) {
                        Log.e("searchEd", "搜索结果" + poiResult.getPois().size());
                        if (errcode == 1000) {
                            if (null != poiResult && poiResult.getPois().size() > 0) {
                                models.clear();
                                for (int i = 0; i < poiResult.getPois().size(); i++) {
                                    models.add(i, new SearchModel(address, poiResult.getPois().get(i).getAdName()
                                            + poiResult.getPois().get(i).getSnippet()
                                            + poiResult.getPois().get(i).getTitle(),
                                            poiResult.getPois().get(i).getLatLonPoint().getLongitude() + "",
                                            poiResult.getPois().get(i).getLatLonPoint().getLatitude() + ""));
                                }
                                models.add(0, new SearchModel(address, address, latLng.longitude + "", latLng.latitude + ""));
                                adapter.setNewData(models);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    public void onPoiItemSearched(PoiItem poiItem, int i) {
                    }
                }
        );
        search.searchPOIAsyn();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dingLocation:
                aMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                break;
            case R.id.search_et:
                Intent intent=new Intent(mActivity,PioActivity.class);
                intent.putExtra("type",type);
                startActivity(intent);
                break;
        }
    }

    private String address;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null
                && aMapLocation.getErrorCode() == 0) {
            address = aMapLocation.getAddress();
            Log.i("address", "地址 " + address);
            latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            doSearchQuery(address);
            if (mListener != null) {
                mListener.onLocationChanged(aMapLocation);// 显示系统箭头
            }
        }
    }

    public static void start(Context context, String type){
        Intent intent=new Intent(context,MapActivity.class);
        intent.putExtra("type",type);
        context.startActivity(intent);
    }
}
